import { inject, ref } from 'vue';

export function useGlobalLoading() {
  const setGlobalLoading = inject('setGlobalLoading') as ((loading: boolean) => void) | undefined;
  const globalLoading = inject('globalLoading') as any;

  const loading = ref(false);

  const showLoading = () => {
    loading.value = true;
    if (setGlobalLoading) {
      setGlobalLoading(true);
    }
  };

  const hideLoading = () => {
    loading.value = false;
    if (setGlobalLoading) {
      setGlobalLoading(false);
    }
  };

  const withLoading = async <T>(asyncFn: () => Promise<T>): Promise<T> => {
    showLoading();
    try {
      const result = await asyncFn();
      return result;
    } finally {
      hideLoading();
    }
  };

  return {
    loading,
    showLoading,
    hideLoading,
    withLoading,
    globalLoading,
  };
} 